package logic

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"vueAdmin/application/model"
	"vueAdmin/application/utils"
)

type menu struct {
	Id       int    `json:"id"`
	Pid      int    `json:"pid"`
	Name     string `json:"name"`
	Path     string `json:"path"`
	Children []menu `json:"children"`
}

func toTree(ori []map[string]string, now *[]menu, pid string) {
	for _, v := range ori {
		if pid == v["menu_pid"] {
			var temp = new(menu)
			tempId, _ := strconv.Atoi(v["id"])
			temp.Id = tempId
			temp.Name = v["menu_name"]
			temp.Path = v["menu_path"]
			tempPid, _ := strconv.Atoi(v["menu_pid"])
			temp.Pid = tempPid
			var child []menu
			child = make([]menu, 0)
			temp.Children = make([]menu, 0)
			toTree(ori, &child, v["id"])
			for _, vv := range child {
				temp.Children = append(temp.Children, vv)
			}
			*now = append(*now, *temp)
		}
	}
}

func GetMenu(c *gin.Context) {
	id, _ := c.Get("user_id")
	originList := model.GetMenu(id.(string))
	var menuTree []menu
	menuTree = make([]menu, 0)
	toTree(originList, &menuTree, "0")
	c.JSON(http.StatusOK, utils.SetPackageData(0, struct {
		List []menu `json:"list"`
	}{List: menuTree}))
}
